import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { siteconfigApi } from '/@/api/siteconfig';
import { useIdCardParser } from './useCardParser';

export interface IdCardOcrResult {
  // 身份证人像面信息
  BirthDate?: string;
  Gender?: string;
  IdNumber?: string;
  Name?: string;
  Nationality?: string;
  Address?: string;
  // 身份证国徽面信息
  IdCardExpiryDate?: string;
  IssuingAuthority?: string;
  [key: string]: any;
}

export interface IdCardOcrOptions {
  /**
   * 是否自动填充实体数据
   * @default true
   */
  autoFill?: boolean;
  /**
   * 是否显示成功消息
   * @default true
   */
  showMessage?: boolean;
  /**
   * 识别成功回调
   */
  onSuccess?: (result: IdCardOcrResult, cardType: 'front' | 'back') => void;
  /**
   * 识别失败回调
   */
  onError?: (error: any, cardType: 'front' | 'back') => void;
}

/**
 * 身份证OCR识别hooks
 * @param options 配置选项
 */
export function useIdCardOcr(options: IdCardOcrOptions = {}) {
  const { parseAndFill } = useIdCardParser();

  const loading = ref(false);
  const error = ref<string | null>(null);

  const {
    autoFill = true,
    showMessage = true,
    onSuccess,
    onError
  } = options;

  /**
   * 识别身份证
   * @param imageId 图片ID
   * @param cardType 卡片类型：front-正面，back-反面
   * @param targetEntity 目标实体对象（可选，用于自动填充）
   */
  const recognizeIdCard = async (
    imageId: string,
    cardType: 'front' | 'back',
    targetEntity?: any
  ): Promise<IdCardOcrResult | null> => {
    if (!imageId) {
      return null;
    }

    loading.value = true;
    error.value = null;

    try {
      // 调用身份证识别API
      const response = await siteconfigApi().recognizeIdentityCard({
        ImageId: imageId,
        CardType: cardType,
      });

      const result: IdCardOcrResult = response.Data;

      // 自动填充实体数据
      if (autoFill && targetEntity) {
        fillEntityData(result, cardType, targetEntity);
      }

      // 显示成功消息
      if (showMessage) {
        ElMessage.success(`身份证${cardType === 'front' ? '正面' : '反面'}识别成功`);
      }

      // 执行成功回调
      onSuccess?.(result, cardType);

      return result;
    } catch (err) {
      const errorMessage = `身份证${cardType === 'front' ? '正面' : '反面'}识别失败、重新上传清晰的身份证照片`;
      error.value = errorMessage;

      if (showMessage) {
        ElMessage.error(errorMessage);
      }

      // 执行错误回调
      onError?.(err, cardType);

      console.error('身份证识别失败:', err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 填充实体数据
   * @param result OCR识别结果
   * @param cardType 卡片类型
   * @param entity 目标实体
   */
  const fillEntityData = (result: IdCardOcrResult, cardType: 'front' | 'back', entity: any) => {
    if (cardType === 'front') {
      // 处理正面信息
      const { BirthDate, Gender, IdNumber, Name, Nationality, Address, } = result;

      // 解析身份证日期格式 (如: "20130506" -> Date)
      const parseBirthDate = (dateStr: string) => {
        if (!dateStr) return null;

        // 如果是8位数字格式 (如: "20130506")
        if (/^\d{8}$/.test(dateStr)) {
          const year = dateStr.substring(0, 4);
          const month = dateStr.substring(4, 6);
          const day = dateStr.substring(6, 8);
          return new Date(`${year}-${month}-${day}`);
        }

        // 尝试直接解析
        return new Date(dateStr);
      };

      const parsedBirthDate = BirthDate ? parseBirthDate(BirthDate) : null;

      // 填充基本信息
      Object.assign(entity, {
        BirthDate: parsedBirthDate,
        Gender,
        IdCardNo: IdNumber,
        Name,
        Ethnicity: Nationality ? `${Nationality}族` : '',
        HouseholdRegistration: Address,
        NativePlace: Address, // 籍贯
        ArchiveAgeDate: parsedBirthDate && !isNaN(parsedBirthDate.getTime()) ? parsedBirthDate : null // 档案年龄日期
      });
      console.log(entity, 'entity');
      // 使用身份证解析器填充年龄等信息
      if (IdNumber) {
        parseAndFill(IdNumber, entity);
      }
    } else if (cardType === 'back') {
      // 处理反面信息
      const { IdCardExpiryDate, IssuingAuthority } = result;

      if (IdCardExpiryDate) {
        entity.IdCardExpiryDate = IdCardExpiryDate;
      }

      if (IssuingAuthority) {
        entity.IssuingAuthority = IssuingAuthority;
      }
    }
  };

  /**
   * 识别身份证人像面
   * @param imageId 图片ID
   * @param targetEntity 目标实体对象
   */
  const recognizeFront = async (imageId: string, targetEntity?: any) => {
    return recognizeIdCard(imageId, 'front', targetEntity);
  };

  /**
   * 识别身份证国徽面
   * @param imageId 图片ID
   * @param targetEntity 目标实体对象
   */
  const recognizeBack = async (imageId: string, targetEntity?: any) => {
    return recognizeIdCard(imageId, 'back', targetEntity);
  };

  /**
   * 重置状态
   */
  const reset = () => {
    loading.value = false;
    error.value = null;
  };

  return {
    loading,
    error,
    recognizeIdCard,
    recognizeFront,
    recognizeBack,
    reset,
  };
} 
